﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.IO;

namespace KC.Business.Stockmaster
{
    public static class Web
    {
        public enum NetworkType { Facebook, Twitter, LinkedIn, Flickr, YouTube, EAv }

        public static int GetSocialScore(string ticker, string username, string password)
        {
            string page = GetEavProfileString(ticker, username, password);
            
            string facebook, twitter;
            Dictionary<NetworkType, int> scores = ScrapeProfile(page, out twitter, out facebook);
            int result = 0;
            foreach (KeyValuePair<NetworkType, int> key in scores)
                result += key.Value;
            return result;
        }
        public static bool IsWorthBuying(string ticker, string username, string password)
        {
            string page = GetEavProfileString(ticker, username, password);
            string twitter, facebook;
            Dictionary<NetworkType, int> result = ScrapeProfile(page, out twitter, out facebook);
            
            if (string.IsNullOrEmpty(twitter))
                return false;
            return IsWorthBuying(twitter);
        }
        public static bool IsWorthBuying(string twitterAddress)
        {
            string page = string.Empty;

            twitterAddress = twitterAddress.Replace("twitter.com", "mobile.twitter.com");

            CookieContainer cookies = new CookieContainer();

            Uri uri = new Uri(twitterAddress);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.KeepAlive = true;
            request.CookieContainer = cookies;
            request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; BOIE9;ENUSSEM)";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            CookieCollection cookieCollection = new CookieCollection();

            if (request.HaveResponse && response.StatusCode == HttpStatusCode.OK)
            {
                StreamReader loginReader = new StreamReader(response.GetResponseStream());
                page = loginReader.ReadToEnd();
            }

            if (!string.IsNullOrEmpty(page))
            {
                try
                {
                    string followingSubstring = page.Substring(page.IndexOf(twitterAddress + "/following"));
                    followingSubstring = followingSubstring.Remove(followingSubstring.IndexOf("</a>"));
                    followingSubstring = followingSubstring.Substring(followingSubstring.IndexOf("Following:"));
                    followingSubstring = followingSubstring.Replace("Following:", string.Empty);

                    string followersSubstring = page.Substring(page.IndexOf(twitterAddress + "/followers"));
                    followersSubstring = followersSubstring.Remove(followersSubstring.IndexOf("</a>"));
                    followersSubstring = followersSubstring.Substring(followersSubstring.IndexOf("Followers:"));
                    followersSubstring = followersSubstring.Replace("Followers:", string.Empty);

                    int followers = int.Parse(followersSubstring);
                    int following = int.Parse(followingSubstring);

                    if (following > 100 && followers > 100)
                    {
                        return true;
                    }
                }
                catch
                {
                    return false;
                }
            }

            return false;
        }

        public static string GetEavProfileString(string ticker, string userName, string password)
        {
            string baseURL = "http://www.empireavenue.com/";

            if (string.IsNullOrEmpty(ticker)) throw new ArgumentNullException("ticker");
            if (string.IsNullOrEmpty(userName)) throw new ArgumentNullException("userName");
            if (string.IsNullOrEmpty(password)) throw new ArgumentNullException("password");
            return GetPage(baseURL + ticker, userName, password);
        }
        private static Dictionary<NetworkType, int> ScrapeProfile(string page, out string TwitterPage, out string FacebookPage)
        {
            bool hasFacebook = false, hasTwitter = false;
            int facebookScore = -1, twitterScore = -1;
            string facebookAddress = string.Empty, twitterAddress = string.Empty;

            hasFacebook = page.Contains("twitter-top");
            hasTwitter = page.Contains("facebook-top");

            if (hasFacebook) {
                facebookAddress = RetrieveUserConnections(page, "facebook-top", "</div>");
                facebookScore = RetrieveUserConnectionScore(page, "facebook-bottom", "</div>"); }
            if (hasTwitter) {
                twitterAddress = RetrieveUserConnections(page, "twitter-top", "</div>");
                twitterScore = RetrieveUserConnectionScore(page, "twitter-bottom", "</div>"); }

            Dictionary<NetworkType, int> result = new Dictionary<NetworkType, int>();
            if (facebookScore >= 0) result.Add(NetworkType.Facebook, facebookScore);
            if (twitterScore >= 0) result.Add(NetworkType.Twitter, twitterScore);

            FacebookPage = facebookAddress;
            TwitterPage = twitterAddress;
            return result;
        }
        private static string RetrieveUserConnections(string pageSource, string startPoint, string endPoint)
        {
            if (!pageSource.Contains(startPoint))
                return null;
            string address = string.Empty;
            string startDiv = pageSource.Substring(pageSource.IndexOf(startPoint));
            startDiv = startDiv.Remove(startDiv.IndexOf(endPoint));
            address = startDiv.Substring(startDiv.IndexOf("'") + 1);
            address = address.Remove(address.IndexOf("'")).Replace("'", string.Empty);
            return address;
        }
        private static int RetrieveUserConnectionScore(string pageSource, string startPoint, string endPoint)
        {
            if (!pageSource.Contains(startPoint))
                return 0;
            int score = 0;
            string startDiv = pageSource.Substring(pageSource.IndexOf(startPoint));
            startDiv = startDiv.Remove(startDiv.IndexOf(endPoint));
            string scoreString = startDiv.Substring(startDiv.IndexOf("')\">") + 4);
            scoreString = scoreString.Remove(scoreString.IndexOf("<"));
            int.TryParse(scoreString, out score);
            return score;
        }
        private static string GetPage(string pageLocation, string userName, string password)
        {
            string page = string.Empty;
            CookieContainer cookies = new CookieContainer();
            Uri uri = new Uri(pageLocation);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.KeepAlive = true;
            request.CookieContainer = cookies;
            request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; BOIE9;ENUSSEM)";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            CookieCollection cookieCollection = new CookieCollection();
            if (request.HaveResponse && response.StatusCode == HttpStatusCode.OK)
            {
                StreamReader loginReader = new StreamReader(response.GetResponseStream());
                page = loginReader.ReadToEnd();
                string formSubstring = page.Substring(page.IndexOf("<form"));
                formSubstring = formSubstring.Remove(formSubstring.IndexOf(">"));
                formSubstring = formSubstring.Substring(formSubstring.IndexOf("http"));
                formSubstring = formSubstring.Remove(formSubstring.IndexOf("\""));
                string loginSubstring = page.Substring(page.IndexOf("<label>E-mail / Ticker</label>"));
                loginSubstring = loginSubstring.Remove(loginSubstring.IndexOf("/>"));
                loginSubstring = loginSubstring.Substring(loginSubstring.IndexOf("name=\"") + 6);
                loginSubstring = loginSubstring.Remove(loginSubstring.IndexOf("\" "));
                string passwordSubstring = page.Substring(page.IndexOf("<label>Password</label>"));
                passwordSubstring = passwordSubstring.Remove(passwordSubstring.IndexOf("/>"));
                passwordSubstring = passwordSubstring.Substring(passwordSubstring.IndexOf("name=\"") + 6);
                passwordSubstring = passwordSubstring.Remove(passwordSubstring.IndexOf("\" "));
                if (response.Cookies.Count > 0)
                {
                    cookieCollection.Add(response.Cookies);
                    response.Close();
                }
                Uri loginURI = new Uri(formSubstring);
                string postData = string.Format("{0}={1}&{2}={3}", loginSubstring, userName, passwordSubstring, password);
                HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create(loginURI);
                loginRequest.ContentType = "application/x-www-form-urlencoded";
                loginRequest.Method = "POST";
                loginRequest.UserAgent =
                "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; BOIE9;ENUSSEM)";
                loginRequest.KeepAlive = true;
                loginRequest.AllowAutoRedirect = true;
                loginRequest.CookieContainer = new CookieContainer();
                loginRequest.CookieContainer.Add(cookieCollection);
                byte[] bytedata = Encoding.UTF8.GetBytes(postData);
                loginRequest.ContentLength = bytedata.Length;
                Stream requestStream = loginRequest.GetRequestStream();
                requestStream.Write(bytedata, 0, bytedata.Length);
                requestStream.Close();
                HttpWebResponse loginResponse = (HttpWebResponse)loginRequest.GetResponse();

                if (loginRequest.HaveResponse && loginResponse.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader secureReader = new StreamReader(loginResponse.GetResponseStream());
                    page = secureReader.ReadToEnd();
                }
                response.Close();
                loginResponse.Close();
            }
            return page;
        }

    }
}
